public class Solution1583 {
    public int unhappyFriends(int n, int[][] preferences, int[][] pairs) {
        int res = 0;
        int[] indexPair = new int[n+1];
        for (int[] pair:pairs) {
            int a = pair[0], b = pair[1];
            indexPair[a] = b;
            indexPair[b] = a;
        }
        for (int[] pair : pairs) {
            for (int i = 0; i < 2; i++) {
                int tmpNum = pair[i];
                int otherNum = pair[(i+1)%2];
                int[] tmpPrefer = preferences[tmpNum];
                outer:for (int num:tmpPrefer) {
                    if(num == otherNum){
                        break;
                    }
                    int partner = indexPair[num];//tmpNum, partner
                    int[] preference = preferences[num];
                    for (int obj:preference) {
                        if(obj == partner){
                            break;
                        }
                        if(obj == tmpNum){
                            res++;
                            break outer;
                        }
                    }
                }
            }
        }
        return res;
    }

    public static void main(String[] args) {
        Solution1583 s = new Solution1583();
        System.out.println(s.unhappyFriends(4,
                new int[][]{{1,3,2},{2,3,0},{1,3,0},{0,2,1}}, new int[][]{{1,3},{0,2}}));
    }
}
